<script setup>
import { ref, onMounted } from 'vue'
import { sessionApi, imgCodeApi, loginApi } from '@/commons/api'
import routes from '@/commons/router'
import Msg from '@/components/message'
import Loader from '@/components/loader/Loader.vue'

// 定义是否显示加载中的变量
const loadShow = ref(false)

// 挂载前判断用户是否登录，如果已登录，则直接跳转到主页
onMounted(() => {
  hasLogin()
})

// hasLogin 判断用户是否已经登录，如果已登录，则直接跳转到主页
const hasLogin = async () => {
  loadShow.value = true
  try {
    const res = await sessionApi()
    loadShow.value = false
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      routes.replace('/main')
    } else {
      localStorage.removeItem("token")
    }
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
  
}

// showCode 显示验证码
const codeShow = ref(false)
const showCode = () => {
  if(!codeShow.value) {
    imgCode()
    codeShow.value = true
  }
}

// imgCode 获取验证码
const imgStr = ref('')
const imgCode = async () => {
  const res = await imgCodeApi()
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    imgStr.value = 'data:image/png;base64,' + res.data
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// loginForm 用户登录的账号及密码对象
const loginForm = ref({
  usname: 'sysadmin',
  passwd: '123456',
  chcode: ''
})

// login 用户登录方法
const login = async () => {
  // 校验登录账号、密码及验证码
  const usname = loginForm.value.usname
  const passwd = loginForm.value.passwd
  const chcode = loginForm.value.chcode
  if(usname==='' || usname.length<6 || usname.length>30) {
    Msg({ kind: 'warn', txt: '登录账号不能为空，且长度6-30位之间！'})
    return
  }
  if(passwd==='' || passwd.length<6 || passwd.length>30) {
    Msg({ kind: 'warn', txt: '登录密码不能为空，且长度6-30位之间！'})
    return
  }
  if(chcode==='' || chcode.length!==5) {
    Msg({ kind: 'warn', txt: '请正确输入验证码！'})
    return
  }
  // 将验证码转换为小写
  loginForm.value.chcode = chcode.toLowerCase()
  loadShow.value = true
  // 发送登录请求
  try {
    const res = await loginApi(loginForm.value)
    loadShow.value = false
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      loginForm.value.chcode = ''
      localStorage.setItem("token", res.data)
      Msg({ kind: 'success', txt: '恭喜您，登录成功！' })
      routes.replace('/main')
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}
</script>

<template>
  <div class="login-a">
    <div class="login-b">
      <div class="login-c"><img src="@/assets/img/2.png" alt="Logo" /></div>
      <div class="login-d">
        <div class="login-e"></div>
        <div class="login-f">
          <div class="login-g">请登录</div>
          <div class="login-h">
            <div class="login-i">账号</div>
            <div>
              <i class="iconfont login-j">&#xe8f6;</i>
              <input type="text" v-model="loginForm.usname" maxlength="30" placeholder="请输入登录账号" class="login-k" @keyup.enter="login()" />
            </div>
            <div class="login-i">密码</div>
            <div>
              <i class="iconfont login-j">&#xe8e3;</i>
              <input type="password" v-model="loginForm.passwd" maxlength="30" placeholder="请输入登录密码" class="login-k" @keyup.enter="login()" />
            </div>
            <div class="login-i">验证码</div>
            <div class="login-l">
              <i class="iconfont login-j">&#xe8a8;</i>
              <input type="text" v-model="loginForm.chcode" maxlength="5" placeholder="请输入验证码" class="login-k" @focus="showCode()" @keyup.enter="login()" />
              <div v-if="codeShow" class="login-m" @click="imgCode()"><img :src="imgStr" alt="点击换一个" class="img login-n" /></div>
            </div>
            <div class="login-o" @click="login()">登　　录</div>
          </div>
        </div>
      </div>
      <div class="login-p">Copyright &copy; 2024-2025 成电医星（nmgyx.com）</div>
    </div>
    <loader :loadShow="loadShow" />
  </div>
</template>

<style scoped>
.login-a {height: 100%; overflow: hidden; background-image: url(@/assets/img/1.gif);}
.login-b {width: 1050px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);}
.login-c {height: 50px; text-align: center;}
.login-d {width: 1050px; background-color: #FFF; border-radius: 20px; margin: 20px 0; display: flex; display: -webkit-flex;}
.login-e {width: 600px; height: 400px; background: url('@/assets/img/4.png') no-repeat; border-radius: 20px;}
.login-f {width: 449px; height: 376px; padding-top: 24px; border-left: 1px solid #CCC;}
.login-g {text-align: center; font-size: 24px; color: #0e9be3; letter-spacing: 20px;}
.login-h {padding: 10px 60px;}
.login-i {padding-top: 15px;}
.login-j {position: absolute; margin: 13px 10px 0 14px; font-size: 18px; color: #888;}
.login-k {width: 285px; height: 40px; padding-left: 40px; font-size: 16px;}
.login-k:focus {border: 1px #1b90fb solid;}
.login-l {position: relative;}
.login-m {width: 100px; height: 42px; position: absolute; top: 1px; right: 1px; cursor: pointer;}
.login-n {border-radius: 0 4px 4px 0;}
.login-o {padding: 10px 15px; margin-top: 20px; color: #FFF; background-color: #0e9be3; border: 0; border-radius: 5px; cursor: pointer; text-align: center; font-size: 18px;}
.login-o:hover {background-color: #4098fc;}
.login-p {height: 30px; line-height: 30px; text-align: center; color: #666;}
</style>